<template>
  <div class="view-fill">
    <div v-if="!modifyInfo.visible" class="app-container-flex">
      <full-screen
        v-model="showDialog"
        title="暂估确认单明细"
        :btn-list="fullInfo.btnList"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <el-button
            v-if="
              infoList.data.status === 1 &&
              $permission('estimationConfirmationOrder:submit')
            "
            @click="submit"
            >提交</el-button
          >
          <el-button
            v-if="
              (infoList.data.status === 1 || infoList.data.status === 2) &&
              $permission('estimationConfirmationOrder:update')
            "
            @click="update"
            >修改</el-button
          >
          <el-button
            v-if="
              (infoList.data.status === 2 || infoList.data.status === 3) &&
              $permission('estimationConfirmationOrder:revoke')
            "
            @click="revoke"
            >撤回</el-button
          >

          <el-button
            v-if="
              infoList.data.status === 2 &&
              $permission('estimationConfirmationOrder:examine')
            "
            @click="examine"
            >审核</el-button
          >
          <el-button
            v-if="
              infoList.data.status === 3 &&
              $permission('estimationConfirmationOrder:confirm')
            "
            @click="confirm"
            >确认</el-button
          >
          <el-button
            v-if="
              infoList.data.status === 4 &&
              $permission('estimationConfirmationOrder:revokeOrder')
            "
            @click="estimatedRevoke"
            >暂估撤回</el-button
          >
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="$permission('estimationConfirmationOrder:printDeatils')"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="infoList" />
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')"></Tooltip>
          </div>
          <div class="model-panel-body">
            <div class="flex_full_item">
              <!-- 表格 -->
              <PageTable
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :check-box="false"
                :tab-index="true"
                :field-list="tableInfo.fieldList"
                :isDynamic="true"
              >
              </PageTable>
            </div>
          </div>
        </div>
      </full-screen>
    </div>
    <order-modify
      v-if="modifyInfo.visible"
      :order-id="modifyInfo.id"
      v-model:visible="modifyInfo.visible"
      :receive-id="modifyInfo.receiveId"
      :title="modifyInfo.title"
      @returnModify="returnModify"
    />
    <page-dialog
      v-if="dialogPathInfo.visible"
      :title="dialogPathInfo.title"
      v-model:visible="dialogPathInfo.visible"
      :width="dialogPathInfo.width"
      :bt-loading="dialogPathInfo.btLoading"
      :bt-list="dialogPathInfo.btList"
      @reset="close"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="formInfo.ref"
        :data="formInfo.data"
        :field-list="formInfo.fieldList"
        :rules="formInfo.rules"
        :label-width="formInfo.labelWidth"
      >
        <template v-slot:form-depotName>{{
          dialogPathInfo.row.depotName
        }}</template>
        <template v-slot:form-deptName>{{
          dialogPathInfo.row.deptName
        }}</template>
        <template v-slot:form-transferDepotName>
          <el-input
            v-model="formInfo.data.transferDepotName"
            class="not-mongolia"
            type="input"
            :required="true"
            :disabled="true"
            placeholder="请选择入库仓库"
          >
            <template #append>
              <el-icon @click="selectStoreDepot"><MoreFilled /></el-icon>
            </template>
          </el-input>
        </template>
      </page-form>
      <dialog-table
        v-if="dialogTableInfo.data.length"
        ref="dialogTableRef"
        v-model:data="dialogTableInfo.data"
        :field-list="dialogTableInfo.fieldList"
        :highlight-row="true"
        :tab-index="true"
        :check-box="false"
        :pager="false"
        @handleEvent="handleDialogEvent"
      >
      </dialog-table>
    </page-dialog>
    <select-depot
      v-if="selectDepotInfo.visible"
      v-model:show-dialog="selectDepotInfo.visible"
      :check-box="false"
      :query="selectDepotInfo.query"
      :highlight-row="true"
      :check-lock="true"
      :save-empty="true"
      @callback="selectDepotCallBack"
    />
  </div>
</template>

<script setup name="estimationConfirmationOrderDetail">
import OrderModify from './modify'
import {
  getEstimationConfirmationOrderDetailCustomizeListAll,
  auditEstimationConfirmation,
  submitEstimationConfirmation,
  confirmEstimationConfirmation,
  estimationConfirmationPrintDetail,
  estimationConfirmationExcelDetail,
  getEstimationConfirmationById,
  getDepotCirculationPath,
  estimationConfirmationRevoke,
  estimationConfirmationRevokeOrder,
} from '@/api/stock.js'
import { getCustomizeSetting } from '@/api/customize'
import { orderOpAffairAll } from '@/api/affair'
import { fatchTemplateByCode } from '@/api/base'
import { getDepotsDefault } from '@/api/core'
import { doPrint } from '@/utils/exportUtil.js'
import { selectByCodeAndDept } from '@/api/report.js'
import { updatePrintCount } from '@/api/mapping'

const { proxy } = getCurrentInstance()
const emit = defineEmits()

const props = defineProps(['visible', 'id'])

const detailInfo = reactive({
  data: {},
  visible: false,
})
const infoList = reactive({
  data: {},
  fieldList: [
    { label: '单号', value: 'orderNo', type: 'text' },
    { label: '来源单号', value: 'sourceOrderNo', type: 'text' },
    {
      label: '入库部门',
      value: 'deptName',
      type: 'text',
    },
    { label: '入库仓库', value: 'depotName', type: 'text' },
    { label: '入库时间', value: 'storeTime', type: 'text' },
    { label: '供应商', value: 'supplierName', type: 'text' },
    { label: '状态', value: 'statusValue', type: 'text' },
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'text',
    },
    { label: '备注', value: 'remark', type: 'popover' },
  ],
})
// 过滤相关配置
const filterInfo = reactive({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id,
      },
    },
    queryParams: {},
  },
})

const fullInfo = reactive({
  btnList: [
    /* {
      label: '打印',
      event: print,
      show: proxy.$permission('estimationConfirmationOrder:printDeatils'),
    }, */
    {
      label: '导出excel',
      event: exportExcel,
      show: proxy.$permission('estimationConfirmationOrder:excelDeatils'),
    },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  data: [],
  fieldList: [],
})
const affairTableInfo = reactive({
  api: orderOpAffairAll,
  query: {
    orderType: 88,
    orderId: props.id,
    sort: 'operate_time desc',
  },
})
const dialogTableInfo = reactive({
  data: [],
  fieldList: [{ label: '暂估确认路径', value: 'name' }],
})
// 弹窗相关
const dialogPathInfo = reactive({
  title: '暂估确认',
  visible: false,
  type: '',
  width: '670px',
  btLoading: false,
  row: {},
  path: {},
  btList: [
    { label: '关闭', type: '', icon: '', event: close, show: true },
    {
      label: '保存',
      type: 'primary',
      icon: '',
      disabled: true,
      event: stockAndEstimation,
      saveLoading: false,
      show: true,
    },
  ],
})
const selectDepotInfo = reactive({
  visible: false,
  query: {
    depotAuth: 'id',
    idNot: '',
    status: 1,
    useTypeId: 1,
  },
})
const formInfo = reactive({
  ref: null,
  data: {
    id: '',
    transferDepotName: '',
    transferDeptName: '',
    transferDepotId: '',
    transferDeptId: '',
  },
  fieldList: [
    {
      label: '入库仓库',
      value: 'depotName',
      type: 'slot',
    },
    {
      label: '入库部门',
      value: 'deptName',
      type: 'slot',
    },
    {
      label: '暂估确认仓库',
      value: 'transferDepotName',
      type: 'slot',
    },
    {
      label: '暂估确认部门',
      value: 'transferDeptName',
      type: 'input',
      placeholder: '暂估确认部门',
      disabled: true,
    },
  ],
  rules: {
    transferDepotName: [
      {
        required: true,
        message: '请输入仓库',
        trigger: 'blur',
      },
    ],
  },
  labelWidth: '120px',
})
const modifyInfo = reactive({
  visible: false,
  receiveId: '',
  id: '',
  title: '',
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})

const canRevoke = computed(() => {
  let arr = tableInfo.data.filter((item) => item.canInvalidCalcQty > 0)
  return arr.length
})

let obj = {
  price: {
    label: '单价',
    value: 'price',
    minWidth: '150px',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('estimationConfirmationOrder:price'),
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('estimationConfirmationOrder:price'),
    hidden: true,
  },
  orderNo: {
    label: '单号',
    value: 'orderNo',
    componentType: 'input',
    show: false,
    type: 'column',
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    permission: !proxy.$permission('estimationConfirmationOrder:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()

function returnBack() {
  showDialog.value = false
  emit('returnBack')
}
function returnModify() {
  getMain()
  getList()
}
function getMain() {
  getEstimationConfirmationById(props.id).then((resp) => {
    if (resp && resp.success) {
      infoList.data = resp.data
      if (!resp.data) {
        showDialog.value = false
        emit('returnBack')
      }
      getList()
    }
  })
}

function getList() {
  getEstimationConfirmationOrderDetailCustomizeListAll(filterInfo.query).then(
    (resp) => {
      if (resp && resp.success) {
        tableInfo.data = resp.data
      }
    }
  )
}
function update() {
  //修改
  modifyInfo.id = infoList.data.id
  modifyInfo.receiveId = ''
  modifyInfo.title = '修改暂估确认单'
  modifyInfo.visible = true
}
function revoke() {
  //撤回
  estimationConfirmationRevoke(infoList.data.id).then((res) => {
    if (res && res.success) {
      returnModify()
    }
  })
}

function submit() {
  submitEstimationConfirmation([infoList.data.id]).then((resp) => {
    if (resp && resp.success) {
      returnModify()
    }
  })
}
function examine() {
  //审核
  auditEstimationConfirmation(infoList.data.id).then((res) => {
    if (res && res.success) {
      returnModify()
    }
  })
}
function getDepotsDefaults() {
  let systemConfig = proxy.$store.state.permission.systemConfig
  console.log(systemConfig, 'systemConfig')
  if (systemConfig.default_receive_depot == 1) {
    //查询默认仓库
    getDepotsDefault().then((resp) => {
      if (resp && resp.success) {
        let data = resp.data
        if (data) {
          formInfo.data.transferDepotId = data.id
          formInfo.data.transferDepotName = data.name
          formInfo.data.transferDeptName = data.deptName || ''
          formInfo.data.transferDeptId = data.deptId || ''
          dialogPathInfo.btList[1].disabled = true
          getStorePath()
        }
      }
    })
  } else if (systemConfig.default_receive_depot == 2) {
    let depotName = proxy.$store.state.user.userInfo.coreResourcesVO
      ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceName
      : ''
    formInfo.data.transferDepotName = depotName
    formInfo.data.transferDepotId = proxy.$store.state.user.userInfo
      .coreResourcesVO
      ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceId
      : ''
    let deptName = proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.name
      : ''
    formInfo.data.transferDeptName = deptName
    formInfo.data.transferDeptId = proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.id
      : ''
    if (depotName) {
      dialogPathInfo.btList[1].disabled = true
      getStorePath()
    }
  }
}
function confirm() {
  dialogPathInfo.visible = true
  dialogPathInfo.row = infoList.data
  formInfo.data.id = infoList.data.id
  selectDepotInfo.query.idNot = infoList.data.depotId
  getDepotsDefaults()
}
function estimatedRevoke() {
  proxy
    .$confirm('是否整单暂估撤回？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      //暂估整单撤回
      estimationConfirmationRevokeOrder(infoList.data.id).then((res) => {
        if (res && res.success) {
          returnModify()
        }
      })
    })
}
function handleDialogEvent(event, data) {
  if (event === 'tableClickRow') {
    dialogPathInfo.path = data.value
  }
}
//关闭弹窗
function close() {
  formInfo.data.id = ''
  formInfo.data.transferDepotId = ''
  formInfo.data.transferDeptId = ''
  formInfo.data.transferDepotName = ''
  formInfo.data.transferDeptName = ''
  selectDepotInfo.query.idNot = ''
  dialogTableInfo.data = []
  dialogPathInfo.visible = false
  dialogPathInfo.btList[1].disabled = true
}
//展示明细
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.data = row
  detailInfo.visible = true
}
//选择仓库
function selectStoreDepot() {
  selectDepotInfo.visible = true
}
function selectDepotCallBack(data = undefined) {
  if (data && data.id) {
    formInfo.data.transferDepotId = data.id
    formInfo.data.transferDepotName = data.name
    formInfo.data.transferDeptName = data.deptName || ''
    formInfo.data.transferDeptId = data.deptId || ''
    dialogPathInfo.btList[1].disabled = true
    getStorePath()
  } else {
    formInfo.data.transferDepotId = ''
    formInfo.data.transferDepotName = ''
    formInfo.data.transferDeptName = ''
    formInfo.data.transferDeptId = ''
  }
}
function getStorePath() {
  let param = {
    firstDepotId: formInfo.data.transferDepotId,
    lastDepotId: dialogPathInfo.row.depotId,
  }
  getDepotCirculationPath(param).then((res) => {
    if (res && res.success) {
      dialogTableInfo.data = res.data
      if (res.data.length > 0) {
        dialogPathInfo.path = res.data[0].value
        // proxy.$refs.dialogTableRef.setCurrentRow(res.data[0], true)
      }
      dialogPathInfo.btList[1].disabled = false
    }
  })
}
//入库并移库
function stockAndEstimation() {
  formInfo.ref.validate((valid) => {
    if (valid) {
      let id = formInfo.data.id
      if (dialogTableInfo.data.length) {
        let params = {
          id: id,
          path: dialogPathInfo.path,
        }
        confirmEstimationConfirmation(params).then((res) => {
          if (res && res.success) {
            returnModify()
            close()
          }
        })
      } else {
        let params = {
          id: id,
          path: [dialogPathInfo.row.depotId, formInfo.data.transferDepotId],
        }
        confirmEstimationConfirmation(params).then((res) => {
          if (res && res.success) {
            returnModify()
            close()
          }
        })
      }
    }
  })
}
const templateArr = ref([])
const popoverVisible = ref(false)
//打印
function print() {
  selectByCodeAndDept({
    tempCode: 'estimationConfirmationDetails',
    deptId: infoList.data.deptId,
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            orderId: infoList.data.id,
            orderNo: infoList.data.orderNo,
          },
          callback: printCallback,
          rintCount: true,
          data: {},
        })
      }
    }
  })
  /*  const consumeSourceOrderNo = infoList.data.consumeSourceOrderNo ? 0 : 1
  fatchTemplateByCode({
    resourceCode: 'estimationConfirmationOrder:print',
    isDefault: consumeSourceOrderNo,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPirntData(temp)
    }
  }) */
}
function printCallback() {
  try {
    // 打印成功增加打印次数
    updatePrintCount({
      orderNo: infoList.data.orderNo,
      orderId: props.id,
      tempCode: 'estimationConfirmationDetails',
      orderType: 88,
    })
  } catch (error) {}
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      orderId: infoList.data.id,
      orderNo: infoList.data.orderNo,
    },
    callback: printCallback,
    rintCount: true,
    data: {},
  })
  popoverVisible.value = false
}
function getPirntData(temp) {
  let params = {
    tableKey:
      'estimationConfirmationOrderDetail-com.slip.spd.entity.vo.stock.EstimationConfirmationOrderDetailVO',
    orderIds: [props.id],
  }
  estimationConfirmationPrintDetail(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(
        temp,
        newData,
        !proxy.$permission('estimationConfirmationOrder:price')
      )
    }
  })
}
//导出excel
function exportExcel() {
  estimationConfirmationExcelDetail(filterInfo.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function getCustomize() {
  let param = {
    tableKey:
      'estimationConfirmationOrderDetail-com.slip.spd.entity.vo.stock.EstimationConfirmationOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = res.data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      getMain()
    }
  })
}
</script>
